/**
 * Created by Ysssssss on 2021/5/4.
 */


import React, { PureComponent } from 'react'
import ShoppingMallPreviewShareIcon from "@components/shoppingMall/ShoppingMallPreviewShareIcon";
import {DesignTemplateContext} from "@pages/shoppingMall/ShoppingMallDesignDetailPage";
import {CustomizeDndProvider, DraggableDiv} from "@common/presentational/DndSort";
import {CustomizeDragTarget, CustomizeDropTarget } from "@common/presentational/DndMove";
import BannerListModule, {BannerListPreview} from "@components/shoppingMall/design/BannerListModule";
import MenuListModule, {MenuListPreview} from "@components/shoppingMall/design/MenuListModule";
import TitleModule, {TitlePreview} from "@components/shoppingMall/design/TitleModule";
import ProductListModule, {ProductListPreview} from "@components/shoppingMall/design/ProductListModule";
import CouponModule, {CouponPreview} from "@components/shoppingMall/design/CouponModule";
import {moveToNewIndex} from "@utils/arrayHelper";
import notify from "@utils/tip";
import {getHistoryMatchParams} from "@utils/setUrlQuery";
import {withRouter} from "react-router-dom";
import BilinIcon from "@common/presentational/BilinIcon";

const defaultModuleInfo = {
    banner: {
        bannerList: [],
    },
    feature: {
        menuList: [],
    },
    'column-title': {
        name: '标题名称'
    },
    'column-content': {
        type: 'one-three',
        isSelf: false,
        goods: []
    },
    coupon: {
        show: true
    }
}

@withRouter
class HomeDesign extends PureComponent {
    static contextType = DesignTemplateContext;
    constructor(props, context) {
        super(props, context);

        this.state = {
            selectedUniqueId: 0
        }

        this.moduleRef = []

        const { subNav } = context
        const { platformId } = getHistoryMatchParams(props)
        if (!subNav.includes('home')) {
            props.history.replace(`/shopping-mall/design/${platformId}/detail`)
        }
    }
    onPreviewSelected (uniqueId) {
        this.setState({
            selectedUniqueId: uniqueId
        })
    }

    moveModuleCallback(id, index) {
        const { templateInfo, onChange, getHomeUniqueId } = this.context
        const { home } = templateInfo
        onChange && onChange('home', {
            ...templateInfo.home,
            content: [
                ...home.content.slice(0,index),
                {
                    moduleName: id,
                    ...defaultModuleInfo[id],
                    uniqueId: getHomeUniqueId(),
                },
                ...home.content.slice(index),
            ],
        })
    }

    deleteModule (index) {
        const { templateInfo, onChange } = this.context
        const { home } = templateInfo
        if (home.content.length <= 1) {
            notify('模版至少需要一个组件', 'error')
            return;
        }
        this.setState({
            selectedUniqueId: undefined
        }, () => {
            onChange && onChange('home', {
                ...templateInfo.home,
                content: [
                    ...home.content.slice(0 ,index),
                    ...home.content.slice(index + 1),
                ],
            })
        })
    }

    handleModuleEditChange(index, value) {
        const { onChange, templateInfo } = this.context
        const { home } = templateInfo
        onChange && onChange('home', {
            ...home,
            content: [
                ...home.content.slice(0,index),
                {
                    ...home.content[index],
                    ...value
                },
                ...home.content.slice(index + 1),
            ]
        })
    }

    sortList (dragId, hoverId) {
        const { onChange, templateInfo } = this.context
        const { home } = templateInfo
        let dragIndex = 0
        let hoverIndex = 0
        home.content.forEach((item, i) => {
            if(item.uniqueId === dragId) {
                dragIndex = i
            }
            if(item.uniqueId === hoverId) {
                hoverIndex = i
            }
        })
        console.log({dragIndex, hoverIndex})
        onChange && onChange('home', {
            ...home,
            content: moveToNewIndex(home.content, dragIndex, hoverIndex)
        })
    }

    switchRenderTemplate ({ index, isPreview, mod }) {
        const { selectedUniqueId } = this.state
        switch (mod.moduleName) {
            case 'banner':
                return isPreview ? (
                    <BannerListPreview
                        className={selectedUniqueId === mod.uniqueId ? ' bd-green' : ' bd-white'}
                        onClick={this.onPreviewSelected.bind(this, mod.uniqueId)}
                        bannerInfo={mod}
                    />
                ) : (
                    <BannerListModule
                        key={mod.uniqueId}
                        bannerInfo={mod}
                        index={index}
                        onChange={this.handleModuleEditChange.bind(this)}
                    />
                )
            case 'feature':
                return isPreview ? (
                    <MenuListPreview
                        className={selectedUniqueId === mod.uniqueId ? ' bd-green' : ' bd-white'}
                        onClick={this.onPreviewSelected.bind(this, mod.uniqueId)}
                        menuInfo={mod}
                    />
                ) : (
                    <MenuListModule
                        key={mod.uniqueId}
                        menuInfo={mod}
                        index={index}
                        onChange={this.handleModuleEditChange.bind(this)}
                    />
                )
            case 'column-title':
                return isPreview ? (
                    <TitlePreview
                        className={selectedUniqueId === mod.uniqueId ? ' bd-green' : ' bd-white'}
                        onClick={this.onPreviewSelected.bind(this, mod.uniqueId)}
                        titleInfo={mod}
                    />
                ) : (
                    <TitleModule
                        key={mod.uniqueId}
                        titleInfo={mod}
                        index={index}
                        onChange={this.handleModuleEditChange.bind(this)}
                    />
                )
            case 'column-content':
                return isPreview ? (
                    <ProductListPreview
                        className={selectedUniqueId === mod.uniqueId ? ' bd-green' : ' bd-white'}
                        onClick={this.onPreviewSelected.bind(this, mod.uniqueId)}
                        productInfo={mod}
                    />
                ) : (
                    <ProductListModule
                        key={mod.uniqueId}
                        productInfo={mod}
                        index={index}
                        onChange={this.handleModuleEditChange.bind(this)}
                    />
                )
            case 'coupon':
                return isPreview ? (
                    <CouponPreview
                        className={selectedUniqueId === mod.uniqueId ? ' bd-green' : ' bd-white'}
                        onClick={this.onPreviewSelected.bind(this, mod.uniqueId)}
                    />
                ) : (
                    <CouponModule
                        key={mod.uniqueId}
                        index={index}
                        onChange={this.handleModuleEditChange.bind(this)}
                    />
                )
            default:
                return null
        }
    }

        getModByUniqueId (uniqueId) {
        const { templateInfo } = this.context
        const { home } = templateInfo
        let index = 0
        let mod = null
        home.content.forEach((content, i) => {
            if (content.uniqueId === uniqueId) {
                index = i
                mod = content
            }
        })
        return {
            index,
            mod
        }
    }

    render () {
        const { selectedUniqueId } = this.state
        const { templateInfo } = this.context
        const { home } = templateInfo
        return (
            <CustomizeDndProvider>
                <div className="module-choose-container">
                    <div className="txc mgt-24 ft-12 ft-clr-ml">基础组件</div>
                    <CustomizeDragTarget
                        className="flex-center mgt-36 cur-poi"
                        id="banner"
                        type="module"
                        onDrop={this.moveModuleCallback.bind(this, 'banner')}
                    >
                        <BilinIcon type="design-image-carousel"/>
                        <div className="txc w-100">轮播图</div>
                    </CustomizeDragTarget>
                    <CustomizeDragTarget
                        className="flex-center mgt-36 cur-poi"
                        id="column-content"
                        type="module"
                        onDrop={this.moveModuleCallback.bind(this, 'column-content')}
                    >
                        <BilinIcon type="design-product"/>
                        <div className="txc w-100">商品</div>
                    </CustomizeDragTarget>
                    <CustomizeDragTarget
                        className="flex-center mgt-36 cur-poi"
                        id="feature"
                        type="module"
                        onDrop={this.moveModuleCallback.bind(this, 'feature')}
                    >
                        <BilinIcon type="design-image-nav"/>
                        <div className="txc w-100">图文导航</div>
                    </CustomizeDragTarget>
                    <CustomizeDragTarget
                        className="flex-center mgt-36 cur-poi"
                        id="column-title"
                        type="module"
                        onDrop={this.moveModuleCallback.bind(this, 'column-title')}
                    >
                        <BilinIcon type="design-text"/>
                        <div className="txc w-100">标题文本</div>
                    </CustomizeDragTarget>
                    <div className="txc mgt-48 ft-12 ft-clr-ml">营销组件</div>
                    <CustomizeDragTarget
                        className="flex-center mgt-36 cur-poi"
                        id="coupon"
                        type="module"
                        onDrop={this.moveModuleCallback.bind(this, 'coupon')}
                    >
                        <BilinIcon type="design-coupon"/>
                        <div className="txc w-100">领券中心</div>
                    </CustomizeDragTarget>
                </div>
                <div className="preview-container">
                    <div className="preview-reality home-preview">
                        <ShoppingMallPreviewShareIcon/>
                        <div className="preview-title">商城首页</div>
                        <CustomizeDropTarget index={0} type="module" className="drop-target">将模块放置于此</CustomizeDropTarget>
                        { home.content.map((mod, index) => {
                            if (!this.moduleRef[mod.uniqueId]) this.moduleRef[mod.uniqueId] = {
                                drag: React.createRef(),
                                preview: React.createRef()
                            }
                            return (
                                <DraggableDiv
                                    key={mod.uniqueId}
                                    id={mod.uniqueId}
                                    type="moduleSortList"
                                    dragRef={this.moduleRef[mod.uniqueId].drag}
                                    previewRef={this.moduleRef[mod.uniqueId].preview}
                                    moveItemFunc={this.sortList.bind(this)}
                                    className="home-module-preview"
                                >
                                    <div ref={this.moduleRef[mod.uniqueId].preview}>
                                        { this.switchRenderTemplate({ mod, index, isPreview: true }) }
                                    </div>
                                    <div className={`home-preview-selected-operation${selectedUniqueId === mod.uniqueId ? '' : ' hidden'}`}>
                                        <div className="operation-box" ref={this.moduleRef[mod.uniqueId].drag}>
                                            <BilinIcon type="drag"/>
                                        </div>
                                        <div className="operation-box" onClick={this.deleteModule.bind(this, index)}>
                                            <BilinIcon type="design-delete" />
                                        </div>
                                    </div>
                                    <CustomizeDropTarget index={index + 1} type="module" className="drop-target">拖拽到此松开添加</CustomizeDropTarget>
                                </DraggableDiv>
                            )
                        }) }
                        <img src={require("@assets/image/design-stores.png")} alt="" className="w-100"/>
                    </div>
                </div>
                { selectedUniqueId !== undefined && this.switchRenderTemplate(this.getModByUniqueId(selectedUniqueId)) }
            </CustomizeDndProvider>
        )
    }
}

export default HomeDesign